package cn.cf.kxx.tools;

import android.app.DownloadManager;
import android.content.Context;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Handler;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class OkHttpUtils {
    private static final String CHARSET_NAME = "UTF-8";
    public static final MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
    public static final MediaType fileType = MediaType.parse("application/octet-stream");
    private static final String TAG = "okhttp";
    public static final int MSG_WHAT = 1000;
    public static final int MSG_FINISHED = 1002;

    private String token;
    private static OkHttpUtils mOkHttpUtils;


    public static OkHttpUtils getInstane(String token){
        if(mOkHttpUtils == null){
            mOkHttpUtils  = new OkHttpUtils(token);
        }
        return mOkHttpUtils;
    }

    private OkHttpClient mOkHttpClient;

    OkHttpUtils(String token){
        this.token = token;
        mOkHttpClient = new OkHttpClient();
    }

    /**
     * get方式请求
     * @param url
     * @param TAG
     * @param responseCallback
     */
    public void httpGet(Context ctt, String url, String TAG, Callback responseCallback){
        if(Tools.isWifiProxy(ctt)){
            return;
        }
        Request request = new Request.Builder()
                .url(url).tag(TAG).header("token",this.token)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(responseCallback);
    }

    /**
     * post方式请求
     * @param url
     * @param json
     * @param TAG
     * @param responseCallback
     */
    public void httpPost(Context ctt,String url, String json, String TAG, Callback responseCallback){
        if(Tools.isWifiProxy(ctt)){
            return;
        }
        RequestBody body = RequestBody.create(jsonType, json);
        Request request = new Request.Builder().header("token",this.token).url(url).tag(TAG).post(body).build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(responseCallback);
    }

    /**
     * post方式请求
     * @param url
     * @param data
     * @param TAG
     * @param responseCallback
     */
    public void httpPost(Context ctt, String url, HashMap<String,Object> data, String TAG, Callback responseCallback){
//        RequestBody body = RequestBody.create(jsonType, json);
        if(Tools.isWifiProxy(ctt)){
            return;
        }
//        MultipartBody.Builder builder = new MultipartBody.Builder()
//                .setType(MultipartBody.FORM);

//        for(Map.Entry<String,Object> entry : data.entrySet()){
//            builder.addFormDataPart(entry.getKey(),String.valueOf(entry.getValue()));
//        }

        Request request = new Request.Builder().header("token",this.token).url(url).tag(TAG).post(SetRequestBody(data)).build();

        Call call = mOkHttpClient.newCall(request);
        call.enqueue(responseCallback);

    }


    private RequestBody SetRequestBody(Map<String, Object> BodyParams){
        RequestBody body = null;
        okhttp3.FormBody.Builder formEncodingBuilder=new okhttp3.FormBody.Builder();
        if(BodyParams != null){
            Iterator<String> iterator = BodyParams.keySet().iterator();
            String key = "";
            while (iterator.hasNext()) {
                key = iterator.next().toString();
                formEncodingBuilder.add(key, String.valueOf(BodyParams.get(key)));
            }
        }
        body=formEncodingBuilder.build();
        return body;

    }

    /**
     * 上传
     * @param url
     * @param
     * @param TAG
     * @param files
     * @param responseCallback
     */
    public void fileUpload(Context ctt,String url, HashMap<String,String> data, String TAG, File[] files, Callback responseCallback){
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);

        if(Tools.isWifiProxy(ctt)){
            return;
        }

        RequestBody fileBody;
        for(File file : files){
            fileBody= RequestBody.create(fileType, file);
            builder.addFormDataPart("file",file.getName(),fileBody);
        }
        for(Map.Entry<String,String> entry : data.entrySet()){
            builder.addFormDataPart(entry.getKey(),entry.getValue());
        }

        Request request = new Request.Builder().url(url).tag(TAG).post(builder.build()).build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(responseCallback);
    }



    /**
     * 取消线程
     * @param tag
     */
    public void cancelByTag(String tag){
        for (Call call : mOkHttpClient.dispatcher().queuedCalls())
        {
            if (tag.equals(call.request().tag()))
            {
                call.cancel();
            }
        }
        for (Call call : mOkHttpClient.dispatcher().runningCalls())
        {
            if (tag.equals(call.request().tag()))
            {
                call.cancel();
            }
        }
    }
}
